var addGoods = new Vue({
  el: "#app-ad",
  data: {
    //一级目录
    currentCategory1: "",
    //二级目录
    currentCategory2: {
      secondCategoryName: "暂无分类",
      ID: -1
    },
    currentCategory2_sets: [],
    //特殊分类
    currentSpcCategory: "",
    //商品信息
    good_id: -1,
    good_info: {
      name: "",
      name_store: "",
      price: "",
      inventory: "",
      description: ""
    },

    //主图
    img_main: "../img/main/no_image_avaliable.png",
    //附属图片2
    imgs_subsidiary: [
      "../img/main/no_image_avaliable.png",
      "../img/main/no_image_avaliable.png",
      "../img/main/no_image_avaliable.png",
      "../img/main/no_image_avaliable.png",
      "../img/main/no_image_avaliable.png"
    ],

    primaryCategory: [],
    secondCategory: [],
    specialCategory: [],
    originalChaoticInfo: [],

    //所有商店
    all_stores: [],
    currentStore: {
      name: "下拉选择",
      ID: -1
    },

    //目录结构
    categoryTree: []
  },
  computed: {
    isCategory2Valid: function() {
      return this.currentCategory2.secondCategoryName === "暂无分类";
    }
  },
  methods: {
    //读取cookie判断是否是有修改界面进入
    hasGoodIdInLocalStorage: function() {
      if (window.localStorage.getItem("good_id") == undefined) return false;
      else {
        this.good_id = window.localStorage.getItem("good_id");
        window.localStorage.removeItem("good_id");
        console.log("移除成功");
        return true;
      }
    },
    //得到所有一级目录
    getAllCategory: function() {
      this.$http.get(SERVER_PORT + "requestCategory").then(
        response => {
          //console.log(response.data.data);
          var originalChaoticInfo = response.data.data;
          this.originalChaoticInfo = Object.assign([], originalChaoticInfo);

          for (var index in originalChaoticInfo) {
            var primaryCategoryName = originalChaoticInfo[index].category1_Name;
            var secondCategory = [];

            for (var sub_index in originalChaoticInfo[index].category2) {
              var secondCategoryName =
                originalChaoticInfo[index].category2[sub_index].name;
              var category2_ID =
                originalChaoticInfo[index].category2[sub_index].category2_ID;
              secondCategory.push({
                secondCategoryName: secondCategoryName,
                ID: category2_ID
              });
            }

            this.categoryTree.push({
              primaryCategory: primaryCategoryName,
              secondCategory: secondCategory
            });
          }

          //console.log(this.categoryTree);
          this.currentCategory1 = this.categoryTree[0].primaryCategory;
          if (this.categoryTree[0].secondCategory.length === 0) {
            this.currentCategory2.secondCategoryName = "暂无分类";
          } else {
            this.currentCategory2 = this.categoryTree[0].secondCategory[0];
          }

          //this.sellers = Object.assign([], response.data.data);
          // 响应成功回调
        },
        response => {
          // 响应错误回调
          console.log(response);
        }
      );
    },

    //根据商品ID获取商品数据
    getGoodInfoFromServer: function() {
      console.log(this.good_id);
      this.$http
        .post(
          SERVER_PORT + "requestGoods",
          { goods_ID: this.good_id },
          {
            emulateJSON: true
          }
        )
        .then(
          response => {
            //console.log(response.data.data);
            console.log(response.data.data);
            var good_info_not_dealed = response.data.data[0];
            addGoods.currentStore = addGoods.getStoreById(
              good_info_not_dealed.store_ID
            );
            var currentCateTreeItem = addGoods.getCategoryById(
              good_info_not_dealed.category2_ID
            ).item;
            var currentCate2Index = addGoods.getCategoryById(
              good_info_not_dealed.category2_ID
            ).sub_index;
            addGoods.currentCategory1 = currentCateTreeItem.primaryCategory;
            addGoods.currentCategory2_sets = currentCateTreeItem.secondCategory;
            addGoods.currentCategory2 = addGoods.currentCategory2_sets[
              currentCate2Index
            ];

            // if(this.currentCategory2==""||this.currentCategory2===undefined){
            //     this.currentCategory2="暂无分类";
            //     this.isCategory2Valid=false;
            // }

            //根据得到的数据设置本地显示
            addGoods.good_info = {
              name: good_info_not_dealed.goods_name,
              name_store: addGoods.currentStore.name,
              price: good_info_not_dealed.price,
              inventory: good_info_not_dealed.inventory,
              description: good_info_not_dealed.description
            };

            addGoods.img_main = good_info_not_dealed.image_main;
          },
          response => {
            // 响应错误回调
            console.log(response);
          }
        );
    },

    //获取所有商店信息
    getAllStores: function() {
      this.$http.get(SERVER_PORT + "requestAllStore").then(
        response => {
          var originData = response.data.data;
          for (var index in originData) {
            var name = originData[index].store_name;
            var ID = originData[index].store_ID;
            this.all_stores.push({
              name: name,
              ID: ID
            });
          }
        },
        response => {
          // 响应错误回调
        }
      );
    },

    getStoreById: function(store_id) {
      for (var index in this.all_stores) {
        if (this.all_stores[index].ID == store_id) {
          return this.all_stores[index];
        }
      }
    },

    getCategoryById: function(cate2_id) {
      for (var index in this.categoryTree) {
        for (var sub_index in this.categoryTree[index].secondCategory) {
          var category2Item = this.categoryTree[index].secondCategory[
            sub_index
          ];
          if (category2Item.ID == cate2_id)
            return { item: this.categoryTree[index], sub_index: sub_index };
        }
      }
    },

    //监听一级目录点击事件
    onPriCateClick: function(index) {
      //console.log(index)
      this.currentCategory1 = this.categoryTree[index].primaryCategory;
      this.currentCategory2_sets = this.categoryTree[index].secondCategory;

      if (this.categoryTree[index].secondCategory.length > 0) {
        this.currentCategory2 = this.categoryTree[index].secondCategory[0];
      } else {
        this.currentCategory2 = {
          secondCategoryName: "暂无分类",
          ID: -1
        };
      }
    },

    //监听二级目录点击事件
    onSubCateClick: function(index) {
      //console.log("Second"+ index)
      this.currentCategory2 = this.currentCategory2_sets[index];
    },

    onStoreClick: function(index) {
      //console.log(index)
      this.currentStore = this.all_stores[index];
    },

    onMainImgChange: function(e) {
      // var files = e.target.files || e.dataTransfer.files;
      // if (!files.length)return;
      // this.createImage(files);
      //console.log(e.target.files);

      if (typeof FileReader === "undefined") {
        alert("您的浏览器不支持图片上传，请升级您的浏览器");
        return false;
      }

      var file = e.target.files;
      var image = new Image();
      var vm = this;
      var leng = file.length;

      vm.img_main = file[0];
      console.log(vm.img_main);

      for (var i = 0; i < leng; i++) {
        var reader = new FileReader();
        reader.readAsDataURL(file[i]);
        reader.onload = function(e) {
          //console.log(e.target.result);
          vm.img_main = e.target.result;
        };
      }
    },

    onSubImgChange: function(e) {
      //console.log("Success")
      if (typeof FileReader === "undefined") {
        alert("您的浏览器不支持图片上传，请升级您的浏览器");
        return false;
      }

      this.imgs_subsidiary = Object.assign([], []);

      var file = e.target.files;
      var vm = this;
      var leng = file.length;

      for (var i = 0; i < leng; i++) {
        if (i > 4) break;
        var reader = new FileReader();
        reader.readAsDataURL(file[i]);
        reader.onload = function(e) {
          //console.log(e.target.result);
          vm.imgs_subsidiary.push(e.target.result);
        };
      }
    },

    //提交表单到服务器
    submit: function() {
      console.log("submit");
      // 检查所有的输入是否合法
      var that = this;
      if (isNaN(this.good_info.price) || this.good_info.price == "") {
          Ply.dialog("alert", "价格输入非法，请重新输入").done(function () {
              that.$refs.price.focus();
          });
          return;
      }

      if (isNaN(this.good_info.inventory) || this.good_info.inventory < 0 || this.good_info.inventory == "") {
          Ply.dialog("alert", "库存输入非法，请重新输入").done(function () {
              that.$refs.inventory.focus();
          });
          return;
      }

      if (this.good_info.name == "") {
          Ply.dialog("alert", "请填写商品名称").done(function () {
              that.$refs.name.focus();
          });
          return;
      }

      if (this.good_info.description.length < 20) {
          Ply.dialog("alert", "商品描述太短，请重新输入").done(function () {
              that.$refs.description.focus();
          });
          return;
      }

      if (this.img_main == "../img/main/no_image_avaliable.png") {
          Ply.dialog("alert", "未选择主图片").done(function () {
              that.$refs.name.focus();
          });
          return;
      }

      if (this.currentStore.ID == -1) {
          Ply.dialog("alert", "未选择商家").done(function () {
              that.$refs.name.focus();
          });
          return;
      }

      if (this.currentCategory2.ID == -1) {
          Ply.dialog("alert", "不允许添加该商品，因为它的二级目录不存在").done(function () {
              that.$refs.name.focus();
          });
          return;
      }


      var postData = {
          goods_name: this.good_info.name,
          price: parseFloat(this.good_info.price),
          inventory: parseInt(this.good_info.inventory),
          image_main: this.img_main,
          description: this.good_info.description,
          store_ID: this.currentStore.ID,
          category2_ID: this.currentCategory2.ID,
      }

      console.log(postData)

      this.$http.post(SERVER_PORT + "addGoods", postData, { emulateJSON: true }).then(response => {
        Ply.dialog("alert", "提交成功").done(function () {
          window.location.href="./goodsModification.html";
      });
      },
          response => {
              console.log(response.data)
          });
    },

    reset: function() {
      this.currentCategory1 = this.categoryTree[0].primaryCategory;
      if (this.categoryTree[0].secondCategory.length === 0) {
        this.currentCategory2.secondCategoryName = "暂无分类";
      } else this.currentCategory2 = this.categoryTree[0].secondCategory[0];

      this.good_info.name = "";
      this.good_info.name_store = "";
      this.good_info.description = "";
      this.good_info.price = null;
      this.good_info.inventory = null;
      this.img_main = "../img/main/no_image_avaliable.png";
      this.imgs_subsidiary = [
        "../img/main/no_image_avaliable.png",
        "../img/main/no_image_avaliable.png",
        "../img/main/no_image_avaliable.png",
        "../img/main/no_image_avaliable.png",
        "../img/main/no_image_avaliable.png"
      ];
      this.currentStore = {
        name: "下拉选择",
        ID: -1
      };
    }
  },
  mounted: function() {
    this.getAllCategory();
    this.getAllStores();

    if (this.hasGoodIdInLocalStorage()) {
      this.getGoodInfoFromServer();
    }

    $("#btn").click(function() {
      $("#upform").ajaxForm(function(data, status) {
        console.log(data);
        if (data.code==="success") {
          addGoods.img_main = data.data.url;
          alert("上传成功！");
        } else {
          alert("上传失败！");
        }
      });
    });
    $("#btn2").click(function() {
      $("#upSubform").ajaxForm(function(data, status) {
        console.log(data);
        if (data.code==="success") {
          addGoods.img_main = data.data.url;
          alert("上传成功！");
        } else {
          alert("上传失败！");
        }
      });
    });
  },
});
